import random, logging

from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from celery_tasks.sms.tasks import send_sms_code
from . import constants
from meiduo_mall.libs.yuntongxun.sms import CCP

# 创建日志对象
logger = logging.getLogger('django')


class SMSCodeView(APIView):
    """短信验证码视图
    1、请求方式GET
    2、url /sms_codes/(?P<mobile>1[3-9]\d{9})/
    3、前端参数路径参数
    4、返回响应数据
    """

    def get(self, request, mobile):
        # 1.获取redis的链接对象，通过链接setting文件中定义的redis数据库配置，创建对应的redis对象
        redis = get_redis_connection('verify')
        # 2.尝试从redis中获取短信验证码的标识，用于判断是否超过60s
        sms_flag = redis.get('sms_flag_%s' % mobile)
        if sms_flag:
            # 如果存在，则表示60s内发过短信，则直接返回
            return Response({'message': '发送短信过于频繁'}, status=status.HTTP_400_BAD_REQUEST)
        # 3.生成短信验证码
        sms_code = '%06d' % random.randint(0, 999999)

        # 4.发送短信验证码
        try:
            # 异步任务必须调用delay方法
            send_sms_code.delay(mobile, sms_code)
        except Exception as e:
            logger.error("发送验证码短信[异常][ mobile: %s, message: %s ]" % (mobile, e))
            return Response({"message": "发送短信失败！"}, status=status.HTTP_502_BAD_GATEWAY)
        # 5.保存短信验证码到redis中
        p1 = redis.pipeline()  # 创建一个管道对象
        # 保存短信验证码
        p1.setex('sms_code_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        # 设置短信验证码标识
        p1.setex('sms_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        # 提交数据
        p1.execute()
        return Response({'message': 'OK'})
